package sk.sigp.aobot.base;

import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.beanutils.MethodUtils;

public class HaveListeners<T extends Listener> {

	private List<T> listeners;
	
	public List<T> getListeners() {
		if (listeners == null) {
			listeners = new ArrayList<T>();
		}
		return listeners;
	}
	
	public int size() {
		return getListeners().size();
	}
	
	public void clear() {
		getListeners().clear();
	}
	
	public void addListener(T listener) {
		if (!getListeners().contains(listener))
			getListeners().add(listener);
	}

	public void removeListener(T listener) {
		if (getListeners().contains(listener))
			getListeners().remove(listener);		
	}
	
	public void fireEvent(String eventName, Object... params) {
		try {
			for (Listener listener: getListeners())
				MethodUtils.invokeMethod(listener, eventName, params);
		} catch (NoSuchMethodException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		}
	}
}
